<template>
  <div>
    <!-- 面包屑 -->
    <XtxBread>
      <XtxBreadItem to="/">首页</XtxBreadItem>
      <XtxBreadItem v-if="category.top" :to="`/category/${category.top.id}`">
        {{ category.top.name }}
      </XtxBreadItem>
      <XtxBreadItem v-if="category.sub">{{ category.sub.name }}</XtxBreadItem>
    </XtxBread>
  </div>
</template>

<script>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
export default {
  name: 'SubBread',
  setup() {
    // 通过计算属性从vuex获得顶级和二级类目信息
    const route = useRoute()
    const store = useStore()

    const category = computed(() => {
      // 声明空对象接收分类数据
      const cate = {}

      // 从vuex中获取商品列表
      store.state.category.list.forEach(top => {
        // 如果有顶级分类有子分类
        if (top.children) {
          // 获取子分类
          const sub = top.children.find(sub => sub.id === route.params.id)
          // 如果存在子分类，添加至空对象
          if (sub) {
            cate.top = { id: top.id, name: top.name }
            cate.sub = { id: sub.id, name: sub.name }
          }
        }
      })

      return cate
    })
    return { category }
  }
}
</script>
<style lang='less' scoped>
</style>
